package com.las.bot.cmd.other;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.las.bot.common.Constant;
import com.utils.IdUtil;
import com.utils.ThreadUtil;
import com.jfinal.kit.HttpKit;
import com.las.annotation.BotCmd;
import com.las.cmd.BaseNonCommand;
import com.las.utils.DownImgUtil;
import com.las.utils.JsonUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

@BotCmd(funName = "保存色图", isMatch = false)
public class SaveImgllegalCmd extends BaseNonCommand {

    private static Logger logger = Logger.getLogger(SaveImgllegalCmd.class);

    private ThreadPoolExecutor executor = ThreadUtil.getPool();

    @Override
    public void execute(JSONObject obj, Long userId, Long id, Integer type, String command, ArrayList<String> args) throws Exception {
        logger.info("执行保存色图...");
        JSONArray msgChain = obj.getJSONArray("messageChain");
        if (CollectionUtil.isNotEmpty(msgChain)) {
            Long msgId = null;
            for (int i = 0; i < msgChain.size(); i++) {
                JSONObject jsonObject = msgChain.getJSONObject(i);
                String msgType = jsonObject.getString("type");
                if ("Source".equals(msgType)) {
                    msgId = jsonObject.getLong("id");
                    break;
                }
            }
            if (null != msgId && msgId > 0) {
                for (int j = 0; j < msgChain.size(); j++) {
                    JSONObject jsonObject = msgChain.getJSONObject(j);
                    String msgType = jsonObject.getString("type");
                    if ("Image".equals(msgType)) {
                        String url = jsonObject.getString("url");
                        saveImageJudge(url, userId, id);
                        break;
                    }
                }
            }
        }

    }

    private void saveImageJudge(String url, Long userId, Long id) {
        int start = url.indexOf("//");
        int length = url.substring(0, start).length();
        String preFix = url.substring(0, length);
        String str = url.substring(length + 2);
        str = str.replaceAll("//", "/");
        String finalUrl = preFix + "//" + str;
        executor.execute(() -> {
            Map<String, String> info = new HashMap<>();
            info.put("grant_type", "client_credentials");
            info.put("client_id", "TwGSLNbo6kYrOlApnKL5wZmN");
            info.put("client_secret", "ldUZ8h0lG3t49Ripj4URFZIW3TGcyeR4");
            String result = HttpKit.post("https://aip.baidubce.com/oauth/2.0/token", info, null);
            JSONObject object = JsonUtils.getJsonObjectByJsonString(result);
            String token = object.getString("access_token");

            info = new HashMap<>();
            info.put("access_token", token);
            info.put("imgUrl", finalUrl);
            String result2 = HttpKit.post("https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined", info, null);
            JSONObject object2 = JsonUtils.getJsonObjectByJsonString(result2);
            String judge = object2.getString("conclusion");
            Double v = null;
            boolean tag = false;
            if ("不合规".equals(judge) || "疑似".equals(judge)) {
                // 保存图标记
                tag = true;
                v = object2.getJSONArray("data").getJSONObject(0).getDouble("probability");
            }

            // 之后存入数据到数据库，后续做一些分析以及新功能“订阅”
            if (tag) {
                String objectName = IdUtil.nextId() + Constant.BUCKET_PNG;
                String path = System.getProperty("user.dir");
                logger.info("保存色图到项目本地路径：" + path);

                File file = null;
                try {
                    String fileUrl = DownImgUtil.downLoadFromUrl(finalUrl, objectName, path);
                    file = new File(fileUrl);
                    String endpoint = Constant.HTTPS + Constant.OSS;
                    String accessKeyId = Constant.BUCKET_ID;
                    String accessKeySecret = Constant.BUCKET_KEY;
                    String bucketName = Constant.BUCKET_NAME;
                    // 上传到阿里云OSS
                    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                    ossClient.putObject(bucketName, objectName, file);
                    ossClient.shutdown();
                    // 生成model调用接口保存到远端数据库
                    String imgUrl = Constant.HTTPS + Constant.BUCKET_NAME + "." + Constant.OSS + objectName;
                    Map<String, Object> msgUrl = new HashMap<>();
                    msgUrl.put("id", IdUtil.nextId());
                    msgUrl.put("url", imgUrl);
                    msgUrl.put("user_id", userId);
                    msgUrl.put("group_id", id);
                    msgUrl.put("judge", judge);
                    msgUrl.put("judge_data", result2);
                    msgUrl.put("op", v);
                    String jsonString = JsonUtils.getJsonString(msgUrl);
                    logger.info("需要保存的色图JSON：" + jsonString);
                    HttpKit.post("http://dullwolf.natapp1.cc/setu/save", jsonString);

                } catch (Exception e) {
                    logger.error("保存色图出错：" + e.toString());
                    e.printStackTrace();
                } finally {
                    // 上传成功后需要上传本地图
                    if (null != file && file.exists()) {
                        file.delete();
                    }
                }
            }
        });
    }


}
